package net.ck.hzq;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Message;
import android.support.v7.widget.AppCompatEditText;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.qmuiteam.qmui.widget.dialog.QMUIDialog;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;

import Bean.AddBankCardBean;
import Bean.AddBankCardParamBean;
import Bean.AuthenticationBean;
import Bean.AuthenticationParamBean;
import Utils.HelloWordModel;
import Utils.OCRUtils;
import Utils.SystemDatas;
import Utils.TimeCount;
import Utils.ToastUtil;
import base.BFHandler;
import base.BaseActivity;
import retrofit2.Call;
import retrofit2.Response;
import ui.activity.mine.BankCardAct;

public class AddCardActivity extends BaseActivity implements View.OnClickListener {


    private MyHandler mHandler;

    private TimeCount timeCount;

    private CountDownTimer timer;

    private static final int REQUEST_CODE_BANKCARD = 111;
    private boolean hasGotToken = false;

    private ImageView addbankcard_back, addbankcard_img2;

    private AppCompatEditText addbankcard_edit1, addbankcard_edit2, addbankcard_edit3;

    private Button addbankcard_but1;//第一步的下一步，第二部的下一步，第三部的下一步

    private SharedPreferences sp;

    private TextView addbankcard_txt, addbankcard_txt1;//核对银行卡号,获取验证码

    private TextView addbankcard_title, addbankcard_title2;//头顶标题，副标题
    //请核对卡号信息，如有错误，点击修改

    private LinearLayout addbankcard_linear1, addbankcard_linear2, addbankcard_linear3;

    private ViewGroup layoutBankCardInfo, layoutVerifyCode;

    private int mBankTypeIndex = -1;
    private String mBankType, mBankName, mPhone;
    private TextView bankTypeTv, tel;
    private AppCompatEditText bankNameEt, phoneEt, verifyCodeEt;
    private TextView sendCode;
    Button submit;

    private static class MyHandler extends BFHandler<AddCardActivity> {

        private MyHandler(AddCardActivity target) {
            super(target);
        }

        @Override
        public void handle(AddCardActivity target, Message msg) {

        }
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_addbankcard;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        TobuyApplication.getmInstance().onActivityCreate(this);
        sp = getSharedPreferences("ToBuy", Context.MODE_PRIVATE);
        addbankcard_linear1 = findViewById(R.id.addbankcard_linear1);
        addbankcard_linear2 = findViewById(R.id.addbankcard_linear2);
        addbankcard_linear3 = findViewById(R.id.addbankcard_linear3);
        addbankcard_back = findViewById(R.id.addbankcard_back);
        addbankcard_title2 = findViewById(R.id.addbankcard_title2);
        addbankcard_edit1 = findViewById(R.id.addbankcard_edit1);
        addbankcard_edit2 = findViewById(R.id.addbankcard_edit2);
        addbankcard_edit3 = findViewById(R.id.addbankcard_edit3);
        addbankcard_but1 = findViewById(R.id.addbankcard_but1);

        addbankcard_img2 = findViewById(R.id.addbankcard_img2);
        addbankcard_txt = findViewById(R.id.addbankcard_txt);
        addbankcard_title = findViewById(R.id.addbankcard_title);
        addbankcard_txt1 = findViewById(R.id.addbankcard_txt1);
        addbankcard_but1.setOnClickListener(this);
        addbankcard_back.setOnClickListener(this);
        addbankcard_txt1.setOnClickListener(this);
        addbankcard_img2.setOnClickListener(this);

        // 银行卡信息
        layoutBankCardInfo = findViewById(R.id.layout_card_info);
        bankTypeTv = findViewById(R.id.bank_type_tv);
        bankTypeTv.setOnClickListener(this);
        bankNameEt = findViewById(R.id.bank_name_et);
        phoneEt = findViewById(R.id.phone_et);
        findViewById(R.id.card_info_next_btn).setOnClickListener(this);

        // 验证码
        layoutVerifyCode = findViewById(R.id.layout_verify_code);
        sendCode = findViewById(R.id.send_code);
        verifyCodeEt = findViewById(R.id.et_verify_code);
        sendCode.setOnClickListener(this);
        tel = findViewById(R.id.tel);
        submit = findViewById(R.id.verify_code_next_btn);
        submit.setOnClickListener(this);
    }

//    @Override
//    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
//                                           @NonNull int[] grantResults) {
//        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
//        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
////            initAccessToken();
//        } else {
//            Toast.makeText(getApplicationContext(), "需要android.permission.READ_PHONE_STATE", Toast.LENGTH_LONG).show();
//        }
//    }

    private String card[];
    private String cardNum, cardType, cardBank, cardVerificationCode;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_BANKCARD && resultCode == Activity.RESULT_OK) {
            recBankCard();
        }
    }

    /**
     * 识别银行卡号
     */
    private void recBankCard() {
    }

    private int status = 1;

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.addbankcard_back:
                switch (status) {
                    case 1:
                        finish();
                        break;
                    case 2:
                        addbankcard_linear1.setVisibility(View.VISIBLE);
                        addbankcard_but1.setVisibility(View.VISIBLE);
                        addbankcard_title2.setVisibility(View.VISIBLE);
                        layoutBankCardInfo.setVisibility(View.GONE);
                        status = 1;
                        break;
                    case 3:
                        layoutVerifyCode.setVisibility(View.GONE);
                        layoutBankCardInfo.setVisibility(View.VISIBLE);
                        status = 2;
                        break;
                    case 0:
                        finish();
                        break;
                }
                break;
            case R.id.addbankcard_img2:
//                if (!checkTokenStatus()) {
//                    return;
//                }
//                Intent intent = new Intent(AddCardActivity.this, CameraActivity.class);
//                intent.putExtra(CameraActivity.KEY_OUTPUT_FILE_PATH,
//                        Utils.FileUtil.getSaveFile(getApplication()).getAbsolutePath());
//                intent.putExtra(CameraActivity.KEY_CONTENT_TYPE,
//                        CameraActivity.CONTENT_TYPE_BANK_CARD);
//                startActivityForResult(intent, REQUEST_CODE_BANKCARD);
                OCRUtils.startBankCard(this, REQUEST_CODE_BANKCARD);
                break;
            case R.id.addbankcard_txt1://获取验证码
                AuthenticationParamBean a = new AuthenticationParamBean();
                a.setTelephoneNumber(sp.getString("phonenumber", null));
                Call<AuthenticationBean> userMsgCall2 = HelloWordModel.getInstance(this).getAuthentication(SystemDatas.GetService_URL("getAuthentication"), a);
                userMsgCall2.enqueue(new retrofit2.Callback<AuthenticationBean>() {
                    @Override
                    public void onResponse(Call<AuthenticationBean> call, final Response<AuthenticationBean> response) {
                        try {
                            if (response.body().getMsg().equals("success")) {
                                Toast.makeText(AddCardActivity.this, "获取成功!", Toast.LENGTH_SHORT).show();
                                cardVerificationCode = response.body().getData().getCode();
                                timeCount = new TimeCount(addbankcard_txt1, 60000, 1000);
                                timeCount.start();
                            } else {
                                Toast.makeText(AddCardActivity.this, response.body().getMsg(), Toast.LENGTH_SHORT).show();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(Call<AuthenticationBean> call, Throwable t) {

                    }
                });
                break;
            case R.id.addbankcard_but1:
                if (TextUtils.isEmpty(addbankcard_edit2.getText())) {
                    Toast.makeText(AddCardActivity.this, "请输入银行卡号!", Toast.LENGTH_SHORT).show();
                    return;
                }
                //校验e
                if (!checkBankCard(addbankcard_edit2.getText().toString().trim().replace(" ", ""))) {
                    ToastUtil.show(AddCardActivity.this, "卡号校验失败");
                    return;
                }
                status = 2;
                cardNum = addbankcard_edit2.getText().toString().trim();
                addbankcard_linear1.setVisibility(View.GONE);
                addbankcard_but1.setVisibility(View.GONE);
                addbankcard_title2.setVisibility(View.GONE);
                layoutBankCardInfo.setVisibility(View.VISIBLE);

                break;

            case R.id.bank_type_tv:
                showSelectBankTypeDialog();
                break;
            case R.id.card_info_next_btn:
                try {
                    String phone = phoneEt.getText().toString();
                    phone = phone.substring(0, 3) + "****" + phone.substring(7, 11);
                    tel.setText(phone);
                } catch (Exception e) {
                    tel.setText("************");
                }
                showVerifyCodePage();
                break;
            case R.id.send_code:
                sendVerifyCode();
                break;
            case R.id.verify_code_next_btn:
                submitData();
                break;
        }

    }

    private void showSelectBankTypeDialog() {
        String[] items = new String[]{"借记卡", "信用卡"};
        new QMUIDialog.CheckableDialogBuilder(this)
                .setCheckedIndex(mBankTypeIndex)
                .addItems(items, (dialogInterface, i) -> {
                    mBankType = items[i];
                    bankTypeTv.setText(mBankType);
                    bankTypeTv.setTextColor(getResources().getColor(R.color.tc_333333));
                    mBankTypeIndex = i;
                    dialogInterface.dismiss();
                })
                .create()
                .show();
    }

    private void showVerifyCodePage() {
        if (TextUtils.isEmpty(bankNameEt.getText())
                || TextUtils.isEmpty(phoneEt.getText())
                || TextUtils.isEmpty(bankTypeTv.getText())) {
            Toast.makeText(AddCardActivity.this, "请填写必要信息", Toast.LENGTH_SHORT).show();
            return;
        }
        status = 3;
        mBankName = bankNameEt.getText().toString();
        mPhone = phoneEt.getText().toString();
        layoutBankCardInfo.setVisibility(View.GONE);
        layoutVerifyCode.setVisibility(View.VISIBLE);
    }

    /**
     * 发送手机验证码
     */
    private void sendVerifyCode() {
        if (timer != null) {
            timer.cancel();
        }
        sendCode.setEnabled(false);
        timer = new CountDownTimer(60000, 1000) {
            @Override
            public void onTick(long l) {
                sendCode.setText(l / 1000 + "秒后重发");
            }

            @Override
            public void onFinish() {
                sendCode.setEnabled(true);
                sendCode.setText("获取验证码");
            }
        };
        timer.start();
        AuthenticationParamBean a = new AuthenticationParamBean();
//        a.setTelephoneNumber(sp.getString("phonenumber", null));
        a.setTelephoneNumber(mPhone);
        Call<AuthenticationBean> userMsgCall2 = HelloWordModel.getInstance(this).getAuthentication(SystemDatas.GetService_URL("getAuthentication"), a);
        userMsgCall2.enqueue(new retrofit2.Callback<AuthenticationBean>() {
            @Override
            public void onResponse(Call<AuthenticationBean> call, final Response<AuthenticationBean> response) {
                try {
                    if (response.body().getMsg().equals("success")) {
                        showSuccessTipDialog("获取成功");
                        cardVerificationCode = response.body().getData().getCode();
                    } else {
                        showFailureTipDialog(response.body().getMsg());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<AuthenticationBean> call, Throwable t) {
                showFailureTipDialog("验证码获取失败,请稍后再试");
            }
        });
    }

    /**
     * 添加银行卡
     */
    private void submitData() {
        if (TextUtils.isEmpty(verifyCodeEt.getText())
                || !verifyCodeEt.getText().toString().equals(cardVerificationCode)) {
            Toast.makeText(AddCardActivity.this, "请输入正确的验证码!", Toast.LENGTH_SHORT).show();
            return;
        }
        submit.setEnabled(false);
        AddBankCardParamBean ap = new AddBankCardParamBean();
        ap.setBankName(mBankName);
        ap.setCardNumber(cardNum);
        ap.setCustomId(Integer.parseInt(sp.getString("id", null)));
//        ap.setPhone(sp.getString("phonenumber", null));
        ap.setPhone(mPhone);
        ap.setType(mBankType);
        Call<AddBankCardBean> userMsgCall4 = HelloWordModel.getInstance(this).addBancard(SystemDatas.GetService_URL("addbankcard"), ap);
        userMsgCall4.enqueue(new retrofit2.Callback<AddBankCardBean>() {
            @Override
            public void onResponse(Call<AddBankCardBean> call, final Response<AddBankCardBean> response) {
                try {
                    if (response.body().getMsg().equals("success")) {
                        Toast.makeText(AddCardActivity.this, "添加成功!", Toast.LENGTH_SHORT).show();
//                        EventBus.getDefault().post(new AddCardEvent());
                        finish();
                        Intent intent = new Intent(AddCardActivity.this, BankCardAct.class);
                        startActivity(intent);
                    } else {
                        Toast.makeText(AddCardActivity.this, response.body().getMsg(), Toast.LENGTH_SHORT).show();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                submit.setEnabled(true);
            }

            @Override
            public void onFailure(Call<AddBankCardBean> call, Throwable t) {
                Toast.makeText(AddCardActivity.this, "添加失败!", Toast.LENGTH_SHORT).show();
                submit.setEnabled(true);
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        OCR.getInstance(this).release();
        if (timer != null) {
            timer.cancel();
        }
    }

    public class AuthService {

        /**
         * 获取权限token
         *
         * @return 返回示例：
         * {
         * "access_token": "24.460da4889caad24cccdb1fea17221975.2592000.1491995545.282335-1234567",
         * "expires_in": 2592000
         * }
         */
        public String getAuth() {
            // 官网获取的 API Key 更新为你注册的
            String clientId = "SltCTTeoHFapGQU26uz7bZsP";
            // 官网获取的 Secret Key 更新为你注册的
            String clientSecret = "mFp5xxMbklRqwGsZE5p5t3vfYBDxeSS0";
            return getAuth(clientId, clientSecret);
        }

        /**
         * 获取API访问token
         * 该token有一定的有效期，需要自行管理，当失效时需重新获取.
         *
         * @param ak - 百度云官网获取的 API Key
         * @param sk - 百度云官网获取的 Securet Key
         * @return assess_token 示例：
         * "24.460da4889caad24cccdb1fea17221975.2592000.1491995545.282335-1234567"
         */
        public String getAuth(String ak, String sk) {
            // 获取token地址
            String authHost = "https://aip.baidubce.com/oauth/2.0/token?";
            String getAccessTokenUrl = authHost
                    // 1. grant_type为固定参数
                    + "grant_type=client_credentials"
                    // 2. 官网获取的 API Key
                    + "&client_id=" + ak
                    // 3. 官网获取的 Secret Key
                    + "&client_secret=" + sk;
            try {
                URL realUrl = new URL(getAccessTokenUrl);
                // 打开和URL之间的连接
                HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
                connection.setRequestMethod("GET");
                connection.connect();
                // 获取所有响应头字段
                Map<String, List<String>> map = connection.getHeaderFields();
                // 遍历所有的响应头字段
                for (String key : map.keySet()) {
                    System.err.println(key + "--->" + map.get(key));
                }
                // 定义 BufferedReader输入流来读取URL的响应
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String result = "";
                String line;
                while ((line = in.readLine()) != null) {
                    result += line;
                }

                System.err.println("result:" + result);
                JSONObject jsonObject = new JSONObject(result);
                String access_token = jsonObject.getString("access_token");
                return access_token;
            } catch (Exception e) {
                System.err.printf("获取token失败！");
                e.printStackTrace(System.err);
            }
            return null;
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    public static char getBankCardCheckCode(String nonCheckCodeCardId) {
        if (nonCheckCodeCardId == null || nonCheckCodeCardId.trim().length() == 0
                || !nonCheckCodeCardId.matches("\\d+")) {
            //如果传的不是数据返回N
            return 'N';
        }
        char[] chs = nonCheckCodeCardId.trim().toCharArray();
        int luhmSum = 0;
        for (int i = chs.length - 1, j = 0; i >= 0; i--, j++) {
            int k = chs[i] - '0';
            if (j % 2 == 0) {
                k *= 2;
                k = k / 10 + k % 10;
            }
            luhmSum += k;
        }
        return (luhmSum % 10 == 0) ? '0' : (char) ((10 - luhmSum % 10) + '0');
    }

    public static boolean checkBankCard(String cardId) {
        char bit = getBankCardCheckCode(cardId.substring(0, cardId.length() - 1));
        if (bit == 'N') {
            return false;
        }
        return cardId.charAt(cardId.length() - 1) == bit;
    }


}
